# coding:utf-8
#
#

import sqlite3
from flask import Flask,request,render_template,jsonify,json

app = Flask(__name__)

def get_db():
    db = sqlite3.connect('raspberry.db')
    db.row_factory = sqlite3.Row
    return db

def query_db(query,args=(),one=False):
    db = get_db()
    cur = db.execute(query,args)
    db.commit()
    rv = cur.fetchall()
    db.close()
    return (rv[0] if rv else None) if one else rv

@app.route("/",methods=["GET"])
def index():
    return render_template("index.html")





@app.route("/home",methods=["GET"])
def home():
    return render_template("home.html")

@app.route("/data",methods=["GET","POST"])
def data():
    res = query_db("select operatetime,value from raspberry where type='cuptemp'")
    return jsonify(time = [x[0] for x in res],
                   cputemp = [x[1] for x in res])

@app.route("/data1",methods=["GET","POST"])
def data1():
    rows = int(request.values.get('rows'))
    page = int(request.values.get('page'))
    offset = rows*(page-1)
    result = {}
    re = query_db("select count(id) from raspberry where type='cuptemp'")
    result["total"] = [x[0] for x in re]
    res = query_db("select id,operatetime,value from raspberry where type='cuptemp' limit %d,%d" % (offset,rows))
    items = []
    for i in res:
        data = {'id' : i[0] , 'time' : i[1],'value' : i[2]}
        items.append(data)
    result["rows"] = items
    return jsonify(result)


if __name__ == '__main__':
    app.run(debug=True)